package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.*;
import com.epfresh.supplier.dialog.AgentSwitchDialog;
import com.epfresh.supplier.entity.AgentMyRecord;
import com.epfresh.supplier.entity.SaveEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.WrapContentLinearLayoutManager;

/**
 * Created by zzq on 2017/12/4.
 */
public class AgentMoneyDetailActivity extends BaseActivity {

    //列表数据
    List<Object> mItems = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    AgentMyRecordViewBinder agentMyApplyViewBinder;
    LinearLayoutManager mManager;
    RecyclerView rv;
    private String mBaseStoreId;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("baseStoreId", mBaseStoreId);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_agent_record);
        if (savedInstanceState != null) {
            getIntent().putExtra("baseStoreId", savedInstanceState.getString("baseStoreId"));
        }
        basetitle.setText("代办费明细");
        mBaseStoreId = getIntent().getStringExtra("baseStoreId");
        initHeadView();
        rv = (RecyclerView) findViewById(R.id.rv_make_agent);
        mManager = new WrapContentLinearLayoutManager(this);

        rv.setLayoutManager(mManager);
        mMultiAdapter = new MultiTypeAdapter();
        agentMyApplyViewBinder = new AgentMyRecordViewBinder();
        agentMyApplyViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if(data instanceof AgentMyRecord.ProductsBean)
                    bean = (AgentMyRecord.ProductsBean)data;
                switch (view.getId()){
                    case R.id.rl_agent_record_goods:

                        Intent intent = new Intent(mContext, BaseProductDetailActivity.class);
                        intent.putExtra("baseStoreId", mBaseStoreId);
                        intent.putExtra("productId", bean.getId());
                        startActivity(intent);
                    case R.id.tv_agent_apply_go:

                        break;
                    case R.id.goods_agent_record_sw:
                        openGoodsAgentStoreDialog(bean.getTitle());
                        break;
                }
            }
        });
        mMultiAdapter.register(AgentMyRecord.ProductsBean.class, agentMyApplyViewBinder);
        rv.setAdapter(mMultiAdapter);
        mMultiAdapter.setItems(mItems);
        reqCommissions();

    }

    /**
     * 这个是针对单个商品代办
     */
    private void openGoodsAgentStoreDialog(String goodsName) {
        final AgentSwitchDialog goodsAgentDialog = new AgentSwitchDialog(this, true);
        if (bean.getState() == 0) {
            goodsAgentDialog.setTitle("是否开启商品代办？");
            goodsAgentDialog.setMessage("开启代办后，将接收" + goodsName + "代办订单");
        } else {
            goodsAgentDialog.setTitle("是否暂停商品代办？");
            goodsAgentDialog.setMessage("如暂停代办，将不会有新的" + goodsName + "的代办订单 但是正在进行中的订单请完成");
        }
        goodsAgentDialog.setOnPositiveClickListener("确定", new AgentSwitchDialog.onPositiveClickListener() {
            @Override
            public void onPositiveClickListener() {
                goodsAgentDialog.dismiss();
                switchGoodsStoreState() ;

            }

        });
        goodsAgentDialog.setOnNegativeClickListener("取消", new AgentSwitchDialog.onNegativeClickListener() {
            @Override
            public void onNegativeClickListener() {
                goodsAgentDialog.dismiss();
                mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
            }
        });
        goodsAgentDialog.show();
    }

    /**
     * 店铺单个商品的代办状态
     * storeId  基地id
     * productId 商品id
     * agentStoreId  代办店铺id
     * state 商品状态
     */
    private void switchGoodsStoreState() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_GOODS_AGENT_STATES);
        RequestEntityMapSupply.putParameter("storeId", mBaseStoreId);
        RequestEntityMapSupply.putParameter("productId", bean.getId());
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());

        if (bean.getState() == 0)
            RequestEntityMapSupply.putParameter("state", 1);
        else {
            RequestEntityMapSupply.putParameter("state", 0);
        }
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_GOODS_AGENT_STATES, onGoodsSwitchRequestListener);
    }

    private OnRequestListener<SaveEntity> onGoodsSwitchRequestListener = new OnRequestListener<SaveEntity>() {
        @Override
        public SaveEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, SaveEntity.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<SaveEntity> response, Object tag) {
            hideProgressDialog();
            SaveEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                if (bean.getState() == 0) {
                    bean.setState(1);
                    reqCommissions();
                }
                else{
                    bean.setState(0);
                    mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
                }

            } else {
                T.toast("设置失败，请稍后重试");
            }
        }
    };


    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            reqCommissions();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.fragment_ptr_agent_record);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }
    AgentMyRecord.ProductsBean bean;

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    private void reqCommissions() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_BASE_COMMISSIONS);
        RequestEntityMapSupply.putParameter("storeId",mBaseStoreId);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_BASE_COMMISSIONS, onApplyRecordRequestListener);
    }

    private OnRequestListener<List<AgentMyRecord.ProductsBean>> onApplyRecordRequestListener = new OnRequestListener<List<AgentMyRecord.ProductsBean>>() {
        @Override
        public List<AgentMyRecord.ProductsBean> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<AgentMyRecord.ProductsBean>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<List<AgentMyRecord.ProductsBean>> response, Object tag) {
            ptrFrameLayout.refreshComplete();
            List<AgentMyRecord.ProductsBean> responseElement = response.getResponseElement();
            mItems.clear();
            mItems.addAll(responseElement);
            mMultiAdapter.notifyDataSetChanged();

        }
    };

}
